import Vue from 'vue'
import Vuex from 'vuex'
import { getInfo, login, setInfo } from '../api/auth';
import { setToken } from '../utils/token';

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        token: '',
        nickname: '',
        head_image: '',
        tag: [],
        tomato: 0,
        allow_stop: false,
    },
    mutations:{
        LOGIN_SUCCESS(state, token) {
            state.token = token;
        },
        SET_INFO(state, info) {
            const { nickname, tag, tomato, head_image, allow_stop } = info;
            state.nickname = nickname;
            state.tag = tag;
            state.tomato = tomato;
            state.head_image = head_image;
            state.allow_stop = allow_stop;
        }
    },
    actions:{
        login() {
            return new Promise(async (resolve, reject) => {
                wx.login({
                    async success(res) {
                        const req = await login(res.code);
                        const data = req.data;
                        if (data.success) {
                            setToken(data.token);
                            store.commit('LOGIN_SUCCESS', data.token);
                            resolve();
                        } else {
                            console.error(data.message);
                            reject('登陆失败！');
                        }
                    },
                    fail(err) {
                        console.error(err);
                        reject('登陆失败！');
                    }
                })
            })
        },
        async logout() {

        },
        async getInfo() {
            let data;
            try {
                const req = await getInfo();
                data = req.data;
                
            } catch (err) {
                console.error(err);
            }
            
            if (data.success) {
                data.tomato = data.property.tomato;
                this.commit('SET_INFO', data);
            } else {
                    console.error(data.message)
                    throw data;
            }
           
        },
        async setInfo({commit}, option) {
            console.log(option)
            const { tag, nickname, allow_stop, head_image } = option;
            let data;
            try {
                const req = await setInfo(tag, nickname, head_image, allow_stop);
                data = req.data;
            } catch(err) {
                console.error(err);
            }
            if (data.success) {
                commit("SET_INFO", { tag, nickname, allow_stop, head_image });
            } else {
                console.error(data.message);
                throw new Error(data);
            }
        }
    }
})
export default store